package com.ws.client.controller;

import com.ws.client.model.BillFormatCustomizeRepire;
import com.ws.client.model.CElement;
import com.ws.client.model.DBSET;
import com.ws.client.model.Order;
import feign.jaxb.JAXBContextFactory;
import org.apache.axis.client.Call;
import org.apache.axis.client.Service;
import org.apache.axis.encoding.XMLType;
import org.w3c.dom.Document;

import javax.xml.namespace.QName;
import javax.xml.rpc.ParameterMode;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.StringWriter;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import static javax.xml.soap.SOAPConstants.DEFAULT_SOAP_PROTOCOL;

public class MainClass {
    private static Charset charsetEncoding = StandardCharsets.UTF_8;
    private static String soapProtocol = DEFAULT_SOAP_PROTOCOL;

    private static final JAXBContextFactory jaxbContextFactory = new JAXBContextFactory.Builder()
            .withMarshallerJAXBEncoding("UTF-8")
            .build();

    /**

    public static void main(String[] args) {
        try {
            Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
            Element element = document.createElement("DATA");
            Element ORDER = document.createElement("ORDER");
            Attr attr = document.createAttributeNS("www.baidu.com","table");
            attr.setNodeValue("234234");
            CDATASection cdataSection = document.createCDATASection("data");
            Attr attrs = document.createAttribute("attrs");
            attrs.setValue("121");
            attrs.setNodeValue("23423");
            attrs.setTextContent("dsfas");
            Element talas = document.createElementNS("wwww.baidu.com1", "talas");
            element.setAttribute("C","APP_NO");
            element.setNodeValue("test");
            element.setAttributeNodeNS(attr);
            element.setAttributeNode(attrs);
            ORDER.appendChild(element);
            document.appendChild(ORDER);
            System.out.println(toFormatedXML(document));
            SOAPMessage soapMessage = MessageFactory.newInstance(soapProtocol).createMessage();
            soapMessage.setProperty("javax.xml.soap.write-xml-declaration", Boolean.toString(true));
            soapMessage.setProperty("javax.xml.soap.character-set-encoding", charsetEncoding.displayName());
            //SOAPEnvelope soapEnvelope = soapMessage.getSOAPPart().getEnvelope();
            //soapEnvelope.addNamespaceDeclaration("targetNamespace", "http://WebXml.com.cn/");
            soapMessage.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, charsetEncoding.displayName());
            soapMessage.getSOAPBody().addDocument(document);
            ByteArrayOutputStream bos = new ByteArrayOutputStream();
            soapMessage.writeTo(bos);
            System.out.println(new String(bos.toByteArray()));
        } catch (SOAPException | ParserConfigurationException | IOException | TransformerFactoryConfigurationError e) {
            throw new EncodeException(e.toString(), e);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
     *
     * @param args
     */
    public static void main(String[] args) {
        Order<BillFormatCustomizeRepire> order = new Order();
        order.setServiceCode("SVC2001");
        order.setSource("WX");
        order.setTarget("sdfasdf");
        List<BillFormatCustomizeRepire> billFormatCustomizeRepireList = new ArrayList<>();
        for (int i = 0; i < 10; i++) {
            BillFormatCustomizeRepire billFormatCustomizeRepire = new BillFormatCustomizeRepire();
            billFormatCustomizeRepire.setAppNo("123131");
            billFormatCustomizeRepire.setCancelDate(new Date());
            billFormatCustomizeRepire.setCancelRean("测试机器");
            order.setData(billFormatCustomizeRepire);
            billFormatCustomizeRepireList.add(billFormatCustomizeRepire);
        }
        order.setDatas(billFormatCustomizeRepireList);
        System.out.println(XmlUtils.convertToXml(order));
        Order<BillFormatCustomizeRepire> order1 = (Order<BillFormatCustomizeRepire>) XmlUtils.convertXmlStrToObject(Order.class,doGetOrderXmlStr());
        System.out.println(order1.getData().getAppNo());;


        DBSET dbset = new DBSET();
        List<CElement> cElements = new ArrayList<>();
        for (int i = 0; i < 5; i++) {
            CElement cElement = new CElement();
            cElement.setAppNo("NAME"+i);
            cElement.setValue("value"+i);
            cElements.add(cElement);
        }
        dbset.setcElementList(cElements);

        System.out.println(XmlUtils.beanToXml(dbset));
        DBSET dbset1 = new DBSET();
        dbset1 = XmlUtils.xmlToBean(doGetDBSETXmlStr(),dbset1);
        System.out.println(dbset1.getcElementList().get(0).getValue());;
        callMethod("http://www.webxml.com.cn/webservices/qqOnlineWebService.asmx","http://WebXml.com.cn/","qqCheckOnline",XmlUtils.beanToXml(dbset));
    }

    public static String doGetOrderXmlStr(){
        String str = "<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n" +
                "<ORDER>\n" +
                "    <servicecode>SVC2001</servicecode>\n" +
                "    <source>WX</source>\n" +
                "    <target>sdfasdf</target>\n" +
                "    <data>\n" +
                "        <appNo>123131</appNo>\n" +
                "        <cancelDate>2020-05-23T11:02:58.691+08:00</cancelDate>\n" +
                "        <cancelRean>测试机器</cancelRean>\n" +
                "    </data>\n" +
                "</ORDER>";
        return str;
    }

    public static String doGetDBSETXmlStr(){
        String str = "<DBSET>\n" +
                "    <R>\n" +
                "        <C N=\"NAME0\">value0</C>\n" +
                "        <C N=\"NAME1\">value1</C>\n" +
                "        <C N=\"NAME2\">value2</C>\n" +
                "        <C N=\"NAME3\">value3</C>\n" +
                "        <C N=\"NAME4\">value4</C>\n" +
                "    </R>\n" +
                "</DBSET>";
        return str;
    }

    public static String toFormatedXML(Document object) throws Exception {
        Document doc = (Document) object;
        TransformerFactory transFactory = TransformerFactory.newInstance();
        Transformer transFormer = transFactory.newTransformer();
        transFormer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
        DOMSource domSource = new DOMSource(doc);

        StringWriter sw = new StringWriter();
        StreamResult xmlResult = new StreamResult(sw);

        transFormer.transform(domSource, xmlResult);

        return sw.toString();

    }

    /**
     * 调用webservice服务
     * @param url url, 不需要带 ?wsdl 后缀
     * @param targetNamespace 对应xml文件的targetNamespace
     * @param methodName 方法名
     * @return map
     */
    public static String callMethod(String url, String targetNamespace, String methodName, String xmlParam) {
        try {
            Service service = new Service();
            Call call = (Call) service.createCall();

            call.addParameter("in0", XMLType.XSD_STRING, ParameterMode.IN);
            call.setTargetEndpointAddress(url);
            //设置要调用哪个方法
            call.setOperationName(new QName(targetNamespace, methodName));
            //设置参数名称
            //要返回的数据类型
            // 调用服务，并传参
            String webServiceResult = (String)call.invoke(new Object[]{xmlParam});
            System.out.println(webServiceResult);
            return webServiceResult;
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}
